package com.jxd.dianping.recommend;

import org.apache.spark.ml.classification.LogisticRegressionModel;
import org.apache.spark.ml.linalg.Vector;
import org.apache.spark.ml.linalg.Vectors;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.sources.In;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class RecommendSortService {
    private SparkSession sparkSession;
    private LogisticRegressionModel logisticRegressionModel;

    @PostConstruct
    public void init() {
        sparkSession = SparkSession.builder().master("local").appName("DianpingApp").getOrCreate();
        logisticRegressionModel = LogisticRegressionModel.load("file:///F:\\IdeaProjects\\self-learn\\dianping\\src\\main\\resources\\model\\lrmodel");
    }

    public List<Integer> sort(List<Integer> shopIdList, Integer userId) {
        List<ShopSortModel> shopSortModels = new ArrayList<>();
        for (Integer shopId: shopIdList) {
            // 假数据 从数据库或缓存中得到feature向量
            Vector vector = Vectors.dense(1, 0, 0, 0, 0, 0, 0.6, 1,0,1,0);
            Vector result = logisticRegressionModel.predictProbability(vector); // 概率
            // logisticRegressionModel.predict(vector); // 0或1
            double[] array = result.toArray();
            double score = array[1]; // 正样本
            ShopSortModel shopSortModel = new ShopSortModel();
            shopSortModel.setShopId(shopId);
            shopSortModel.setScore(score);
            shopSortModels.add(shopSortModel);
        }
        shopSortModels.sort(new Comparator<ShopSortModel>() {
            @Override
            public int compare(ShopSortModel o1, ShopSortModel o2) {
                if(o1.getScore() < o2.getScore()) {
                    return 1;
                } else if (o1.getScore() > o2.getScore()) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        return shopSortModels.stream().map(ShopSortModel::getShopId).collect(Collectors.toList());
    }

}
